<?php
// 处理AJAX请求 - 切换常用状态（必须放在最顶部，优先处理）
if (isset($_GET['ajax']) && $_GET['ajax'] === 'toggle_favorite') {
    require_once dirname(__DIR__) . '/config/config.php';
    require_once dirname(__DIR__) . '/includes/auth.php';
    require_once dirname(__DIR__) . '/includes/database.php';
    // session已由config/config.php统一管理，无需重复调用
    header('Content-Type: application/json');
    if (!isset($_SESSION['admin_username'])) {
        echo json_encode(['success' => false, 'error' => '未登录或会话超时']);
        exit;
    }
    // 捕获并处理错误，确保始终返回JSON格式
    try {
        if (!isset($_POST['id']) || !isset($_POST['is_favorite'])) {
            throw new Exception('缺少必要参数');
        }
        $db = new Database();
        $id = (int)$_POST['id'];
        $is_favorite = (int)$_POST['is_favorite'];
        $success = $db->setNavigationFavorite($id, $is_favorite);
        if (!$success) {
            throw new Exception('更新导航常用状态失败');
        }
        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        writeLog('切换常用状态失败: ' . $e->getMessage(), 'ERROR');
        echo json_encode([
            'success' => false,
            'error' => $e->getMessage()
        ]);
    }
    exit;
}

// 修复路径问题 - 使用绝对路径
$adminDir = __DIR__;
$projectRoot = dirname($adminDir);

require_once $projectRoot . '/config/config.php';
require_once $projectRoot . '/includes/auth.php';
require_once $projectRoot . '/includes/database.php';

// session已由config/config.php统一管理，无需重复调用

// 检查登录状态
requireLogin();

// 简单的重定向函数
function redirect($url) {
    header("Location: " . $url);
    exit;
}

// 初始化数据库
$db = new Database();

// 获取系统设置（包含动态标题）
$settings = $db->getSettings();
$siteTitle = $settings['site_title'] ?? SITE_TITLE;

// 处理文件上传
function handleImageUpload($file) {
    if (!isset($file) || $file['error'] !== UPLOAD_ERR_OK) {
        return false;
    }
    
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'ico', 'svg'];
    $filename = $file['name'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    if (!in_array($ext, $allowed)) {
        return false;
    }
    
    $newName = uniqid() . '.' . $ext;
    $uploadPath = ICON_DIR . '/' . $newName;
    
    if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
        return getUrl('uploads/icons/' . $newName);
    }
    
    return false;
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $icon = '';
        $iconType = $_POST['icon_type'] ?? 'class';
        
        if ($iconType === 'upload' && isset($_FILES['icon_file'])) {
            $uploadResult = handleImageUpload($_FILES['icon_file']);
            if ($uploadResult) {
                $icon = $uploadResult;
                $iconType = 'url';
            } else {
                $error = '图标上传失败！';
            }
        } elseif ($iconType === 'link') {
            $icon = sanitizeInput($_POST['icon_link']);
        } else {
            $icon = sanitizeInput($_POST['icon']);
        }
        
        if (!isset($error)) {
            // 处理多分类选择
            $categoryIds = [];
            if (isset($_POST['category_ids']) && is_array($_POST['category_ids'])) {
                $categoryIds = array_map('intval', $_POST['category_ids']);
            } elseif (isset($_POST['category_id'])) {
                $categoryIds = [(int)$_POST['category_id']];
            }

            // 处理标签选择
            $tagIds = [];
            if (isset($_POST['tag_ids']) && is_array($_POST['tag_ids'])) {
                $tagIds = array_map('intval', $_POST['tag_ids']);
            }

            $data = [
                'category_ids' => $categoryIds,
                'category_id' => $categoryIds[0] ?? 1, // 兼容旧版本
                'tag_ids' => $tagIds,
                'name' => sanitizeInput($_POST['name']),
                'url' => sanitizeInput($_POST['url']),
                'icon' => $icon,
                'icon_type' => $iconType,
                'description' => sanitizeInput($_POST['description']),
                'sort' => (int)$_POST['sort'],
                'is_favorite' => isset($_POST['is_favorite']) ? 1 : 0
            ];

            if ($db->addNavigation($data)) {
                $_SESSION['success_message'] = '导航添加成功！';
            } else {
                $_SESSION['error_message'] = '导航添加失败！';
            }
            redirect(getUrl('admin/navigations'));
        } else {
            $_SESSION['error_message'] = $error;
            redirect(getUrl('admin/navigations'));
        }
    } elseif ($action === 'edit') {
        $id = (int)$_POST['id'];
        $icon = $_POST['current_icon'] ?? '';
        $iconType = $_POST['icon_type'] ?? 'class';
        
        if ($iconType === 'upload' && isset($_FILES['icon_file']) && $_FILES['icon_file']['error'] === UPLOAD_ERR_OK) {
            $uploadResult = handleImageUpload($_FILES['icon_file']);
            if ($uploadResult) {
                $icon = $uploadResult;
                $iconType = 'url';
            }
        } elseif ($iconType === 'link') {
            $icon = sanitizeInput($_POST['icon_link']);
        } elseif ($iconType === 'class') {
            $icon = sanitizeInput($_POST['icon']);
        }
        
        // 处理多分类选择
        $categoryIds = [];
        if (isset($_POST['category_ids']) && is_array($_POST['category_ids'])) {
            $categoryIds = array_map('intval', $_POST['category_ids']);
        } elseif (isset($_POST['category_id'])) {
            $categoryIds = [(int)$_POST['category_id']];
        }

        // 处理标签选择
        $tagIds = [];
        if (isset($_POST['tag_ids']) && is_array($_POST['tag_ids'])) {
            $tagIds = array_map('intval', $_POST['tag_ids']);
        }

        $data = [
            'category_ids' => $categoryIds,
            'category_id' => $categoryIds[0] ?? 1, // 兼容旧版本
            'tag_ids' => $tagIds,
            'name' => sanitizeInput($_POST['name']),
            'url' => sanitizeInput($_POST['url']),
            'icon' => $icon,
            'icon_type' => $iconType,
            'description' => sanitizeInput($_POST['description']),
            'sort' => (int)$_POST['sort'],
            'is_favorite' => isset($_POST['is_favorite']) ? 1 : 0
        ];
        
        if ($db->updateNavigation($id, $data)) {
            $_SESSION['success_message'] = '导航更新成功！';
        } else {
            $_SESSION['error_message'] = '导航更新失败！';
        }
        redirect(getUrl('admin/navigations'));
    } elseif ($action === 'delete') {
        $id = (int)$_POST['id'];
        if ($db->deleteNavigation($id)) {
            $_SESSION['success_message'] = '导航删除成功！';
        } else {
            $_SESSION['error_message'] = '导航删除失败！';
        }
        redirect(getUrl('admin/navigations'));
    }
}

// 获取并清除消息
$success_message = $_SESSION['success_message'] ?? null;
unset($_SESSION['success_message']);

$error_message = $_SESSION['error_message'] ?? null;
unset($_SESSION['error_message']);

// 获取数据
$categories = $db->getCategories();

// 分页参数
$perPage = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page); // 确保页码至少为1

// 获取导航总数
$totalNavigations = $db->getNavigationsCount();
$totalPages = ceil($totalNavigations / $perPage);
$page = min($page, $totalPages); // 确保页码不超过最大页数

// 计算偏移量
$offset = ($page - 1) * $perPage;

// 获取当前页的导航数据
$navigations = $db->getNavigations(null, $perPage, $offset);
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>导航管理 - <?php echo $siteTitle; ?></title>
    
    <!-- 样式文件 -->
    <link rel="stylesheet" href="<?php echo asset('css/admin.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('libs/fontawesome/all.min.css'); ?>">
    
    <!-- 网站图标 -->
    <link rel="icon" type="image/x-icon" href="<?php echo asset('images/favicon.ico'); ?>">
</head>
<body class="admin-page">
    <!-- 侧边栏 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo">
                <i class="fas fa-compass"></i>
                <h2><?php echo $siteTitle; ?></h2>
            </div>
        </div>
        
        <nav class="sidebar-nav">
            <ul>
                <li>
                    <a href="<?php echo getUrl('admin/'); ?>">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>仪表盘</span>
                    </a>
                </li>
                <li class="active">
                    <a href="<?php echo getUrl('admin/navigations'); ?>">
                        <i class="fas fa-link"></i>
                        <span>导航管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/categories'); ?>">
                        <i class="fas fa-folder"></i>
                        <span>分类管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/tags'); ?>">
                        <i class="fas fa-tags"></i>
                        <span>标签管理</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl('admin/settings'); ?>">
                        <i class="fas fa-cog"></i>
                        <span>系统设置</span>
                    </a>
                </li>
                <li>
                    <a href="<?php echo getUrl(); ?>" target="_blank">
                        <i class="fas fa-external-link-alt"></i>
                        <span>访问前台</span>
                    </a>
                </li>
            </ul>
        </nav>
        
        <div class="sidebar-footer">
            <div class="user-info">
                <i class="fas fa-user-circle"></i>
                <span><?php echo $_SESSION['admin_username'] ?? 'Admin'; ?></span>
            </div>
            <a href="<?php echo getUrl('admin/index?action=logout'); ?>" class="logout-btn" title="退出登录">
                <i class="fas fa-sign-out-alt"></i>
            </a>
        </div>
    </aside>
    
    <!-- 主要内容区域 -->
    <main class="main-content">
        <!-- 顶部栏 -->
        <header class="content-header">
            <div class="header-left">
                <h1><i class="fas fa-link"></i> 导航管理</h1>
                <p>管理导航链接，支持图标上传和分类设置。</p>
            </div>
            <div class="header-right">
                <button class="btn btn-primary" onclick="showAddModal()">
                    <i class="fas fa-plus"></i> 添加导航
                </button>
            </div>
        </header>
        
        <!-- 消息提示 -->
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle"></i>
                <?php echo $success_message; ?>
            </div>
        <?php endif; ?>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle"></i>
                <?php echo $error_message; ?>
            </div>
        <?php endif; ?>
        
        <!-- 导航列表 -->
        <section class="content-section">
            <div class="card">
                <div class="card-header">
                    <h3><i class="fas fa-list"></i> 导航列表</h3>
                    <p>共 <?php echo $totalNavigations; ?> 个导航 (第 <?php echo $page; ?> 页，共 <?php echo $totalPages; ?> 页)</p>
                </div>
                <div class="card-body">
                    <?php if (!empty($navigations)): ?>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>图标</th>
                                        <th>名称</th>
                                        <th>链接</th>
                                        <th>分类</th>
                                        <th>标签</th>
                                        <th>常用</th>
                                        <th>点击次数</th>
                                        <th>排序</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($navigations as $nav): ?>
                                        <tr>
                                            <td><?php echo $nav['id']; ?></td>
                                            <td>
                                                <?php if ($nav['icon_type'] === 'class'): ?>
                                                    <i class="<?php echo htmlspecialchars($nav['icon']); ?>"></i>
                                                <?php else: ?>
                                                    <img src="<?php echo htmlspecialchars($nav['icon']); ?>" 
                                                         alt="<?php echo htmlspecialchars($nav['name']); ?>"
                                                         style="width: 20px; height: 20px;">
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo htmlspecialchars($nav['name']); ?></td>
                                            <td>
                                                <a href="<?php echo htmlspecialchars($nav['url']); ?>" 
                                                   target="_blank" class="text-primary">
                                                    <?php echo strlen($nav['url']) > 30 ? substr($nav['url'], 0, 30) . '...' : $nav['url']; ?>
                                                </a>
                                            </td>
                                            <td>
                                                <?php 
                                                // 获取导航的所有分类信息
                                                $navCategories = $db->getNavigationCategoriesInfo($nav['id']);
                                                $categoryCount = count($navCategories);
                                                if ($categoryCount > 0): 
                                                ?>
                                                    <div class="category-display">
                                                        <?php 
                                                        // 展示前两个分类
                                                        $showCount = min(2, $categoryCount);
                                                        for ($i = 0; $i < $showCount; $i++): ?>
                                                            <span class="badge category-badge">
                                                                <?php echo htmlspecialchars($navCategories[$i]['name']); ?>
                                                            </span>
                                                        <?php endfor; ?>
                                                        <?php if ($categoryCount > 2): ?>
                                                            <span class="category-count" 
                                                                  onclick="showCategoryModal(<?php echo $nav['id']; ?>, <?php echo htmlspecialchars(json_encode($navCategories)); ?>)">
                                                                +<?php echo $categoryCount - 2; ?>
                                                                <i class="fas fa-external-link-alt"></i>
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted">未分类</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php
                                                // 获取导航的所有标签信息
                                                $navTags = $db->getNavigationTags($nav['id']);
                                                $tagCount = count($navTags);
                                                if ($tagCount > 0):
                                                ?>
                                                    <div class="tag-display">
                                                        <?php
                                                        // 展示前两个标签
                                                        $showCount = min(2, $tagCount);
                                                        for ($i = 0; $i < $showCount; $i++): ?>
                                                            <span class="badge tag-badge">
                                                                <?php echo htmlspecialchars($navTags[$i]['name_cn']); ?>
                                                            </span>
                                                        <?php endfor; ?>
                                                        <?php if ($tagCount > 2): ?>
                                                            <span class="tag-count" title="<?php echo htmlspecialchars(implode(', ', array_column($navTags, 'name_cn'))); ?>">
                                                                +<?php echo $tagCount - 2; ?>
                                                            </span>
                                                        <?php endif; ?>
                                                    </div>
                                                <?php else: ?>
                                                    <span class="text-muted">无标签</span>
                                                <?php endif; ?>
                                            </td>
                                                                        <td>
                                <label class="switch">
                                    <input type="checkbox"
                                           <?php echo (isset($nav['is_favorite']) && $nav['is_favorite'] == 1) ? 'checked' : ''; ?>
                                           onchange="toggleFavorite(<?php echo $nav['id']; ?>, this.checked)">
                                    <span class="slider round"></span>
                                </label>
                            </td>
                                            <td><?php echo $nav['clicks'] ?? 0; ?></td>
                                            <td><?php echo $nav['sort']; ?></td>
                                            <td>
                                                <div class="btn-group">
                                                    <button class="btn btn-sm btn-outline-primary" 
                                                            onclick="editNavigation(<?php echo htmlspecialchars(json_encode($nav)); ?>)">
                                                        <i class="fas fa-edit"></i> 编辑
                                                    </button>
                                                    <button class="btn btn-sm btn-outline-danger" 
                                                            onclick="deleteNavigation(<?php echo $nav['id']; ?>, '<?php echo htmlspecialchars($nav['name']); ?>')">
                                                        <i class="fas fa-trash"></i> 删除
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页导航 -->
                        <?php if ($totalPages > 1): ?>
                        <div class="pagination-container">
                            <nav class="pagination-nav">
                                <ul class="pagination">
                                    <!-- 上一页 -->
                                    <?php if ($page > 1): ?>
                                        <li class="page-item">
                                            <a href="?page=<?php echo $page - 1; ?>" class="page-link">
                                                <i class="fas fa-chevron-left"></i> 上一页
                                            </a>
                                        </li>
                                    <?php else: ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">
                                                <i class="fas fa-chevron-left"></i> 上一页
                                            </span>
                                        </li>
                                    <?php endif; ?>

                                    <!-- 页码 -->
                                    <?php
                                    $startPage = max(1, $page - 2);
                                    $endPage = min($totalPages, $page + 2);

                                    // 如果总页数少于5页，显示所有页码
                                    if ($totalPages <= 5) {
                                        $startPage = 1;
                                        $endPage = $totalPages;
                                    }

                                    // 第一页
                                    if ($startPage > 1): ?>
                                        <li class="page-item">
                                            <a href="?page=1" class="page-link">1</a>
                                        </li>
                                        <?php if ($startPage > 2): ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        <?php endif; ?>
                                    <?php endif; ?>

                                    <!-- 中间页码 -->
                                    <?php for ($i = $startPage; $i <= $endPage; $i++): ?>
                                        <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                            <?php if ($i === $page): ?>
                                                <span class="page-link"><?php echo $i; ?></span>
                                            <?php else: ?>
                                                <a href="?page=<?php echo $i; ?>" class="page-link"><?php echo $i; ?></a>
                                            <?php endif; ?>
                                        </li>
                                    <?php endfor; ?>

                                    <!-- 最后一页 -->
                                    <?php if ($endPage < $totalPages): ?>
                                        <?php if ($endPage < $totalPages - 1): ?>
                                            <li class="page-item disabled">
                                                <span class="page-link">...</span>
                                            </li>
                                        <?php endif; ?>
                                        <li class="page-item">
                                            <a href="?page=<?php echo $totalPages; ?>" class="page-link"><?php echo $totalPages; ?></a>
                                        </li>
                                    <?php endif; ?>

                                    <!-- 下一页 -->
                                    <?php if ($page < $totalPages): ?>
                                        <li class="page-item">
                                            <a href="?page=<?php echo $page + 1; ?>" class="page-link">
                                                下一页 <i class="fas fa-chevron-right"></i>
                                            </a>
                                        </li>
                                    <?php else: ?>
                                        <li class="page-item disabled">
                                            <span class="page-link">
                                                下一页 <i class="fas fa-chevron-right"></i>
                                            </span>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="empty-state">
                            <i class="fas fa-link"></i>
                            <h3>暂无导航</h3>
                            <p>还没有创建任何导航链接，点击上方按钮开始添加。</p>
                            <?php if (empty($categories)): ?>
                                <p class="text-warning">请先创建分类后再添加导航。</p>
                                <a href="<?php echo getUrl('admin/categories'); ?>" class="btn btn-secondary">
                                    <i class="fas fa-folder"></i> 管理分类
                                </a>
                            <?php else: ?>
                                <button class="btn btn-primary" onclick="showAddModal()">
                                    <i class="fas fa-plus"></i> 添加第一个导航
                                </button>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </section>
    </main>
    
    <!-- 添加/编辑导航模态框 -->
    <div id="navigationModal" class="modal">
        <div class="modal-content modal-lg">
            <div class="modal-header">
                <h3 id="modalTitle">添加导航</h3>
                <button class="close-btn" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" enctype="multipart/form-data" class="modal-body" id="navigationForm">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="navigationId">
                <input type="hidden" name="current_icon" id="currentIcon">
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="name">导航名称 *</label>
                            <input type="text" id="name" name="name" required placeholder="请输入导航名称">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="url">链接地址 *</label>
                            <input type="url" id="url" name="url" required placeholder="https://example.com">
                        </div>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="category_ids">所属分类 * <small class="text-muted">(可多选)</small></label>
                            <div class="category-selector">
                                <div class="selected-categories" id="selectedCategories" onclick="toggleCategoryDropdown()">
                                    <span class="placeholder">请选择分类</span>
                                    <i class="fas fa-chevron-down dropdown-arrow"></i>
                                </div>
                                <div class="category-dropdown" id="categoryDropdown">
                                    <?php foreach ($categories as $category): ?>
                                        <label class="category-option">
                                            <input type="checkbox" name="category_ids[]" value="<?php echo $category['id']; ?>" 
                                                   onchange="updateSelectedCategories()">
                                            <span class="checkmark"></span>
                                            <span class="category-name"><?php echo htmlspecialchars($category['name']); ?></span>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            
                            <!-- 隐藏的单选框，保持兼容性 -->
                            <select id="category_id" name="category_id" style="display: none;">
                                <option value="">请选择分类</option>
                                <?php foreach ($categories as $category): ?>
                                    <option value="<?php echo $category['id']; ?>">
                                        <?php echo htmlspecialchars($category['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="sort">排序序号 *</label>
                            <input type="number" id="sort" name="sort" required placeholder="数字越小排序越靠前" min="1">
                        </div>
                    </div>
                </div>

                <!-- 标签选择 -->
                <div class="form-group" id="tagFormGroup" style="display: none;">
                    <label for="tag_ids">所属标签 <small class="text-muted">(可多选，仅显示选中分类下的标签)</small></label>
                    <div class="tag-selector">
                        <div class="selected-tags" id="selectedTags" onclick="toggleTagDropdown()">
                            <span class="placeholder">请选择标签</span>
                            <i class="fas fa-chevron-down dropdown-arrow"></i>
                        </div>
                        <div class="tag-dropdown" id="tagDropdown">
                            <div class="tag-loading" id="tagLoading">
                                <i class="fas fa-spinner fa-spin"></i>
                                <span>加载标签中...</span>
                            </div>
                            <div class="tag-list" id="tagList" style="display: none;">
                                <!-- 标签选项将通过JavaScript动态加载 -->
                            </div>
                            <div class="no-tags" id="noTags" style="display: none;">
                                <i class="fas fa-info-circle"></i>
                                <span>所选分类下暂无标签</span>
                            </div>
                        </div>
                    </div>
                    <small class="form-text text-muted">请先选择分类，然后可以为导航添加多个标签</small>
                </div>
                
                <div class="form-group">
                    <label>图标设置 *</label>
                    <div class="icon-options">
                            <label class="radio-option">
                                <input type="radio" name="icon_type" value="class" checked onchange="toggleIconInput()">
                                <span>Font Awesome 图标</span>
                            </label>
                            <label class="radio-option">
                                <input type="radio" name="icon_type" value="upload" onchange="toggleIconInput()">
                                <span>上传图标文件</span>
                            </label>
                            <label class="radio-option">
                                <input type="radio" name="icon_type" value="link" onchange="toggleIconInput()">
                                <span>网站图标链接</span>
                            </label>
                        </div>
                    
                    <div id="iconClassInput">
                        <div class="icon-input-group">
                            <div class="selected-icon-display" onclick="showIconPicker()">
                                <i id="selectedIconPreview" class="fas fa-question-circle"></i>
                                <div class="icon-display-text">
                                    <span id="selectedIconText">请选择图标</span>
                                    <small class="icon-class-text" id="selectedIconClass">点击选择</small>
                                </div>
                                <i class="fas fa-chevron-down icon-dropdown-arrow"></i>
                            </div>
                            <input type="text" id="icon" name="icon" placeholder="或手动输入：fas fa-star" 
                                   onchange="updateIconPreview(this.value)">
                        </div>
                        <small class="form-text">点击按钮选择图标，或手动输入 Font Awesome 图标类名</small>
                    </div>
                    
                    <div id="iconFileInput" style="display: none;">
                        <label for="icon_file">上传图标</label>
                        <div class="image-preview-container">
                            <img id="imagePreview" src="#" alt="图标预览" style="display: none;">
                            <span id="imagePreviewText">图片预览</span>
                        </div>
                        <input type="file" id="icon_file" name="icon_file" accept="image/*,image/svg+xml">
                        <small>推荐尺寸：64x64px，支持jpg, png, gif, ico, svg</small>
                    </div>
                    
                    <div id="iconLinkInput" style="display: none;">
                        <label for="icon_link">图标链接</label>
                        <div class="image-preview-container">
                            <img id="linkImagePreview" src="#" alt="图标预览" style="display: none;">
                            <span id="linkImagePreviewText">图片预览</span>
                        </div>
                        <input type="url" id="icon_link" name="icon_link" placeholder="https://example.com/favicon.ico" onchange="updateLinkIconPreview(this.value)">
                        <small>支持绝对URL，如网站favicon.ico或其他图片链接</small>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="description">描述信息</label>
                    <textarea id="description" name="description" rows="3" placeholder="请输入导航描述（可选）"></textarea>
                </div>
                
                <div class="form-group">
                    <label for="is_favorite">是否常用导航</label>
                    <div class="switch-container">
                        <label class="switch">
                            <input type="checkbox" id="is_favorite" name="is_favorite" value="1">
                            <span class="slider round"></span>
                        </label>
                        <span class="switch-label">常用导航将在首页搜索框下方显示</span>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 图标选择器模态框 -->
    <div id="iconPickerModal" class="modal">
        <div class="modal-content modal-lg">
            <div class="modal-header">
                <h3>选择 Font Awesome 图标</h3>
                <button class="close-btn" onclick="closeIconPicker()">&times;</button>
            </div>
            <div class="modal-body">
                <div class="icon-search-box">
                    <input type="text" id="iconSearch" placeholder="搜索图标..." onkeyup="filterIcons(this.value)">
                </div>
                <div class="icon-categories">
                    <button class="icon-category-btn" onclick="showIconCategory('recent')">最近使用</button>
                    <button class="icon-category-btn active" onclick="showIconCategory('all')">全部</button>
                    <button class="icon-category-btn" onclick="showIconCategory('common')">常用</button>
                    <button class="icon-category-btn" onclick="showIconCategory('web')">网站</button>
                    <button class="icon-category-btn" onclick="showIconCategory('social')">社交</button>
                    <button class="icon-category-btn" onclick="showIconCategory('business')">商务</button>
                    <button class="icon-category-btn" onclick="showIconCategory('tech')">技术</button>
                </div>
                <div class="icon-grid" id="iconGrid">
                    <!-- 图标将通过JavaScript动态生成 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeIconPicker()">取消</button>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>确认删除</h3>
                <button class="close-btn" onclick="closeDeleteModal()">&times;</button>
            </div>
            <div class="modal-body">
                <p>确定要删除导航 "<span id="deleteNavigationName"></span>" 吗？</p>
                <p class="text-warning">此操作不可恢复！</p>
                <form method="POST" style="display: none;" id="deleteForm">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" id="deleteNavigationId">
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeDeleteModal()">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                    <i class="fas fa-trash"></i> 确认删除
                </button>
            </div>
        </div>
    </div>

    <!-- 分类展示弹窗 -->
    <div id="categoryModal" class="modal">
        <div class="modal-content modal-sm">
            <div class="modal-header">
                <h3><i class="fas fa-tags"></i> 绑定分类</h3>
                <button class="close-btn" onclick="closeCategoryModal()">&times;</button>
            </div>
            <div class="modal-body">
                <div id="categoryModalContent" class="category-modal-list">
                    <!-- 分类列表将通过JavaScript动态填充 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeCategoryModal()">关闭</button>
            </div>
        </div>
    </div>
    
    <script>
        // 兜底定义showAlert，兼容全局和本地
        const showAlert = window.AdminJS && window.AdminJS.showAlert ? window.AdminJS.showAlert : alert;

        // 从localStorage获取最近使用的图标
        function getRecentIcons() {
            const recentIcons = localStorage.getItem('recentIcons');
            return recentIcons ? JSON.parse(recentIcons) : [];
        }
        
        // 保存最近使用的图标
        function saveRecentIcon(iconClass, iconName) {
            const recentIcons = getRecentIcons();
            
            // 移除已存在的相同图标
            const filteredIcons = recentIcons.filter(icon => icon.class !== iconClass);
            
            // 添加到列表开头
            filteredIcons.unshift({ class: iconClass, name: iconName });
            
            // 保留最近10个图标
            const iconsToKeep = filteredIcons.slice(0, 10);
            
            // 保存到localStorage
            localStorage.setItem('recentIcons', JSON.stringify(iconsToKeep));
        }
        
        // Font Awesome 图标数据 (2024年最新版本)
        const fontAwesomeIcons = {
            recent: [], // 将在页面加载时填充
            common: [
                { class: 'fas fa-home', name: '首页' },
                { class: 'fas fa-house', name: '房屋' },
                { class: 'fas fa-user', name: '用户' },
                { class: 'fas fa-users', name: '用户组' },
                { class: 'fas fa-star', name: '星标' },
                { class: 'fas fa-heart', name: '喜欢' },
                { class: 'fas fa-search', name: '搜索' },
                { class: 'fas fa-magnifying-glass', name: '搜索' },
                { class: 'fas fa-envelope', name: '邮件' },
                { class: 'fas fa-phone', name: '电话' },
                { class: 'fas fa-calendar', name: '日历' },
                { class: 'fas fa-calendar-days', name: '日历' },
                { class: 'fas fa-clock', name: '时钟' },
                { class: 'fas fa-location-dot', name: '位置' },
                { class: 'fas fa-map-marker-alt', name: '位置' },
                { class: 'fas fa-shopping-cart', name: '购物车' },
                { class: 'fas fa-cart-shopping', name: '购物车' },
                { class: 'fas fa-download', name: '下载' },
                { class: 'fas fa-upload', name: '上传' },
                { class: 'fas fa-edit', name: '编辑' },
                { class: 'fas fa-pen-to-square', name: '编辑' },
                { class: 'fas fa-trash', name: '删除' },
                { class: 'fas fa-trash-can', name: '删除' },
                { class: 'fas fa-plus', name: '添加' },
                { class: 'fas fa-minus', name: '减少' },
                { class: 'fas fa-check', name: '确认' },
                { class: 'fas fa-xmark', name: '关闭' },
                { class: 'fas fa-times', name: '关闭' },
                { class: 'fas fa-cog', name: '设置' },
                { class: 'fas fa-gear', name: '设置' },
                { class: 'fas fa-info-circle', name: '信息' },
                { class: 'fas fa-circle-info', name: '信息' },
                { class: 'fas fa-exclamation-triangle', name: '警告' },
                { class: 'fas fa-triangle-exclamation', name: '警告' },
                { class: 'fas fa-question-circle', name: '帮助' },
                { class: 'fas fa-circle-question', name: '帮助' },
                { class: 'fas fa-thumbs-up', name: '赞' },
                { class: 'fas fa-thumbs-down', name: '踩' },
                { class: 'fas fa-share', name: '分享' },
                { class: 'fas fa-share-nodes', name: '分享' },
                { class: 'fas fa-link', name: '链接' },
                { class: 'fas fa-eye', name: '查看' },
                { class: 'fas fa-print', name: '打印' },
                { class: 'fas fa-bookmark', name: '书签' },
                { class: 'fas fa-bell', name: '通知' },
                { class: 'fas fa-lock', name: '锁定' },
                { class: 'fas fa-unlock', name: '解锁' },
                { class: 'fas fa-shield', name: '安全' },
                { class: 'fas fa-fire', name: '火热' },
                { class: 'fas fa-bolt', name: '闪电' },
                { class: 'fas fa-tag', name: '标签' },
                { class: 'fas fa-tags', name: '标签组' },
                { class: 'fas fa-flag', name: '旗帜' },
                { class: 'fas fa-copy', name: '复制' },
                { class: 'fas fa-folder', name: '文件夹' },
                { class: 'fas fa-file', name: '文件' },
                { class: 'fas fa-image', name: '图片' },
                { class: 'fas fa-music', name: '音乐' },
                { class: 'fas fa-video', name: '视频' },
                { class: 'fas fa-comment', name: '评论' },
                { class: 'fas fa-comments', name: '聊天' },
                { class: 'fas fa-message', name: '消息' },
                { class: 'fas fa-filter', name: '过滤' },
                { class: 'fas fa-sort', name: '排序' },
                { class: 'fas fa-list', name: '列表' },
                { class: 'fas fa-table', name: '表格' },
                { class: 'fas fa-bars', name: '菜单' },
                { class: 'fas fa-ellipsis', name: '更多' },
                { class: 'fas fa-circle', name: '圆形' },
                { class: 'fas fa-square', name: '方形' },
                { class: 'fas fa-arrows-rotate', name: '刷新' },
                { class: 'fas fa-power-off', name: '电源' }
            ],
            web: [
                { class: 'fab fa-github', name: 'GitHub' },
                { class: 'fab fa-gitlab', name: 'GitLab' },
                { class: 'fab fa-bitbucket', name: 'Bitbucket' },
                { class: 'fab fa-git-alt', name: 'Git' },
                { class: 'fab fa-google', name: 'Google' },
                { class: 'fab fa-microsoft', name: 'Microsoft' },
                { class: 'fab fa-apple', name: 'Apple' },
                { class: 'fab fa-amazon', name: 'Amazon' },
                { class: 'fab fa-aws', name: 'AWS' },
                { class: 'fab fa-digital-ocean', name: 'DigitalOcean' },
                { class: 'fab fa-cloudflare', name: 'Cloudflare' },
                { class: 'fab fa-netflix', name: 'Netflix' },
                { class: 'fab fa-youtube', name: 'YouTube' },
                { class: 'fab fa-stack-overflow', name: 'Stack Overflow' },
                { class: 'fab fa-codepen', name: 'CodePen' },
                { class: 'fab fa-jsfiddle', name: 'JSFiddle' },
                { class: 'fab fa-npm', name: 'NPM' },
                { class: 'fab fa-node-js', name: 'Node.js' },
                { class: 'fab fa-react', name: 'React' },
                { class: 'fab fa-vuejs', name: 'Vue.js' },
                { class: 'fab fa-angular', name: 'Angular' },
                { class: 'fab fa-bootstrap', name: 'Bootstrap' },
                { class: 'fab fa-docker', name: 'Docker' },
                { class: 'fab fa-python', name: 'Python' },
                { class: 'fab fa-java', name: 'Java' },
                { class: 'fab fa-js-square', name: 'JavaScript' },
                { class: 'fab fa-html5', name: 'HTML5' },
                { class: 'fab fa-css3-alt', name: 'CSS3' },
                { class: 'fab fa-sass', name: 'Sass' },
                { class: 'fab fa-less', name: 'Less' },
                { class: 'fab fa-wordpress', name: 'WordPress' },
                { class: 'fab fa-drupal', name: 'Drupal' },
                { class: 'fab fa-joomla', name: 'Joomla' },
                { class: 'fab fa-laravel', name: 'Laravel' },
                { class: 'fab fa-symfony', name: 'Symfony' },
                { class: 'fab fa-figma', name: 'Figma' },
                { class: 'fab fa-sketch', name: 'Sketch' },
                { class: 'fab fa-adobe', name: 'Adobe' },
                { class: 'fab fa-chrome', name: 'Chrome' },
                { class: 'fab fa-firefox', name: 'Firefox' },
                { class: 'fab fa-safari', name: 'Safari' },
                { class: 'fab fa-edge', name: 'Edge' },
                { class: 'fab fa-brave', name: 'Brave' },
                { class: 'fas fa-globe', name: '网站' },
                { class: 'fas fa-earth-americas', name: '全球' },
                { class: 'fas fa-blog', name: '博客' },
                { class: 'fas fa-server', name: '服务器' },
                { class: 'fas fa-database', name: '数据库' },
                { class: 'fas fa-cloud', name: '云服务' },
                { class: 'fas fa-cloud-arrow-up', name: '云上传' },
                { class: 'fas fa-cloud-arrow-down', name: '云下载' },
                { class: 'fas fa-code', name: '代码' },
                { class: 'fas fa-code-branch', name: '代码分支' },
                { class: 'fas fa-terminal', name: '终端' },
                { class: 'fas fa-laptop-code', name: '编程' },
                { class: 'fas fa-bug', name: '调试' },
                { class: 'fas fa-network-wired', name: '网络' },
                { class: 'fas fa-wifi', name: 'WiFi' },
                { class: 'fas fa-ethernet', name: '以太网' },
                { class: 'fas fa-sitemap', name: '网站地图' },
                { class: 'fas fa-window-maximize', name: '窗口' },
                { class: 'fas fa-browser', name: '浏览器' },
                { class: 'fas fa-rocket', name: '发布' }
            ],
            social: [
                { class: 'fab fa-facebook', name: 'Facebook' },
                { class: 'fab fa-x-twitter', name: 'X (Twitter)' },
                { class: 'fab fa-twitter', name: 'Twitter' },
                { class: 'fab fa-instagram', name: 'Instagram' },
                { class: 'fab fa-linkedin', name: 'LinkedIn' },
                { class: 'fab fa-youtube', name: 'YouTube' },
                { class: 'fab fa-tiktok', name: 'TikTok' },
                { class: 'fab fa-snapchat', name: 'Snapchat' },
                { class: 'fab fa-pinterest', name: 'Pinterest' },
                { class: 'fab fa-reddit', name: 'Reddit' },
                { class: 'fab fa-discord', name: 'Discord' },
                { class: 'fab fa-telegram', name: 'Telegram' },
                { class: 'fab fa-whatsapp', name: 'WhatsApp' },
                { class: 'fab fa-wechat', name: '微信' },
                { class: 'fab fa-weixin', name: '微信' },
                { class: 'fab fa-weibo', name: '微博' },
                { class: 'fab fa-qq', name: 'QQ' },
                { class: 'fab fa-slack', name: 'Slack' },
                { class: 'fab fa-threads', name: 'Threads' },
                { class: 'fab fa-mastodon', name: 'Mastodon' },
                { class: 'fab fa-signal-messenger', name: 'Signal' },
                { class: 'fab fa-viber', name: 'Viber' },
                { class: 'fab fa-skype', name: 'Skype' },
                { class: 'fab fa-zoom', name: 'Zoom' },
                { class: 'fab fa-twitch', name: 'Twitch' },
                { class: 'fab fa-medium', name: 'Medium' },
                { class: 'fab fa-tumblr', name: 'Tumblr' },
                { class: 'fab fa-vimeo', name: 'Vimeo' },
                { class: 'fab fa-soundcloud', name: 'SoundCloud' },
                { class: 'fab fa-spotify', name: 'Spotify' },
                { class: 'fab fa-bilibili', name: '哔哩哔哩' },
                { class: 'fab fa-zhihu', name: '知乎' },
                { class: 'fas fa-comment', name: '评论' },
                { class: 'fas fa-comments', name: '聊天' },
                { class: 'fas fa-message', name: '消息' },
                { class: 'fas fa-users', name: '用户群' },
                { class: 'fas fa-at', name: '@符号' },
                { class: 'fas fa-hashtag', name: '话题标签' },
                { class: 'fas fa-share', name: '分享' },
                { class: 'fas fa-share-nodes', name: '分享' }
            ],
            business: [
                { class: 'fas fa-briefcase', name: '公文包' },
                { class: 'fas fa-building', name: '建筑' },
                { class: 'fas fa-building-columns', name: '银行' },
                { class: 'fas fa-industry', name: '工业' },
                { class: 'fas fa-store', name: '商店' },
                { class: 'fas fa-chart-bar', name: '柱状图' },
                { class: 'fas fa-chart-column', name: '柱状图' },
                { class: 'fas fa-chart-line', name: '折线图' },
                { class: 'fas fa-chart-pie', name: '饼图' },
                { class: 'fas fa-chart-area', name: '面积图' },
                { class: 'fas fa-chart-simple', name: '简单图表' },
                { class: 'fas fa-dollar-sign', name: '美元' },
                { class: 'fas fa-yen-sign', name: '日元' },
                { class: 'fas fa-euro-sign', name: '欧元' },
                { class: 'fas fa-pound-sign', name: '英镑' },
                { class: 'fas fa-indian-rupee-sign', name: '印度卢比' },
                { class: 'fas fa-won-sign', name: '韩元' },
                { class: 'fas fa-bitcoin-sign', name: '比特币' },
                { class: 'fas fa-credit-card', name: '信用卡' },
                { class: 'fas fa-money-bill', name: '纸币' },
                { class: 'fas fa-money-bill-wave', name: '纸币波浪' },
                { class: 'fas fa-coins', name: '硬币' },
                { class: 'fas fa-piggy-bank', name: '存钱罐' },
                { class: 'fas fa-wallet', name: '钱包' },
                { class: 'fas fa-cash-register', name: '收银机' },
                { class: 'fas fa-receipt', name: '收据' },
                { class: 'fas fa-handshake', name: '握手' },
                { class: 'fas fa-handshake-simple', name: '简单握手' },
                { class: 'fas fa-trophy', name: '奖杯' },
                { class: 'fas fa-award', name: '奖项' },
                { class: 'fas fa-medal', name: '奖牌' },
                { class: 'fas fa-crown', name: '皇冠' },
                { class: 'fas fa-target', name: '目标' },
                { class: 'fas fa-bullseye', name: '靶心' },
                { class: 'fas fa-rocket', name: '火箭' },
                { class: 'fas fa-lightbulb', name: '灯泡' },
                { class: 'fas fa-calculator', name: '计算器' },
                { class: 'fas fa-balance-scale', name: '天平' },
                { class: 'fas fa-scale-balanced', name: '平衡秤' },
                { class: 'fas fa-gavel', name: '法官锤' },
                { class: 'fas fa-stamp', name: '印章' },
                { class: 'fas fa-signature', name: '签名' },
                { class: 'fas fa-file-contract', name: '合同' },
                { class: 'fas fa-file-invoice', name: '发票' },
                { class: 'fas fa-file-invoice-dollar', name: '费用发票' },
                { class: 'fas fa-clipboard-check', name: '检查清单' },
                { class: 'fas fa-clipboard-list', name: '清单' },
                { class: 'fas fa-tasks', name: '任务' },
                { class: 'fas fa-project-diagram', name: '项目图' },
                { class: 'fas fa-sitemap', name: '架构图' },
                { class: 'fas fa-network-wired', name: '网络' },
                { class: 'fas fa-users-gear', name: '团队管理' },
                { class: 'fas fa-user-tie', name: '商务人员' },
                { class: 'fas fa-user-gear', name: '用户管理' },
                { class: 'fas fa-cogs', name: '配置' },
                { class: 'fas fa-tools', name: '工具' },
                { class: 'fas fa-wrench', name: '扳手' },
                { class: 'fas fa-hammer', name: '锤子' },
                { class: 'fas fa-hard-hat', name: '安全帽' },
                { class: 'fas fa-warehouse', name: '仓库' },
                { class: 'fas fa-shipping-fast', name: '快递' },
                { class: 'fas fa-truck', name: '卡车' },
                { class: 'fas fa-truck-fast', name: '快速配送' },
                { class: 'fas fa-box', name: '包裹' },
                { class: 'fas fa-boxes-stacked', name: '堆叠箱子' },
                { class: 'fas fa-pallet', name: '托盘' },
                { class: 'fas fa-conveyor-belt', name: '传送带' },
                { class: 'fas fa-scale', name: '秤' },
                { class: 'fas fa-percent', name: '百分比' },
                { class: 'fas fa-percentage', name: '百分比' },
                { class: 'fas fa-chart-trending-up', name: '上升趋势' },
                { class: 'fas fa-arrow-trend-up', name: '趋势向上' },
                { class: 'fas fa-arrow-trend-down', name: '趋势向下' }
            ],
            tech: [
                { class: 'fas fa-laptop', name: '笔记本' },
                { class: 'fas fa-laptop-code', name: '编程笔记本' },
                { class: 'fas fa-mobile-alt', name: '手机' },
                { class: 'fas fa-mobile-screen-button', name: '智能手机' },
                { class: 'fas fa-tablet-alt', name: '平板' },
                { class: 'fas fa-tablet-screen-button', name: '智能平板' },
                { class: 'fas fa-desktop', name: '桌面' },
                { class: 'fas fa-computer', name: '电脑' },
                { class: 'fas fa-tv', name: '电视' },
                { class: 'fas fa-display', name: '显示器' },
                { class: 'fas fa-keyboard', name: '键盘' },
                { class: 'fas fa-mouse', name: '鼠标' },
                { class: 'fas fa-computer-mouse', name: '电脑鼠标' },
                { class: 'fas fa-headphones', name: '耳机' },
                { class: 'fas fa-headphones-simple', name: '简单耳机' },
                { class: 'fas fa-headset', name: '耳麦' },
                { class: 'fas fa-microphone', name: '麦克风' },
                { class: 'fas fa-microphone-lines', name: '麦克风线条' },
                { class: 'fas fa-camera', name: '相机' },
                { class: 'fas fa-camera-retro', name: '复古相机' },
                { class: 'fas fa-video', name: '视频' },
                { class: 'fas fa-video-camera', name: '摄像机' },
                { class: 'fas fa-photo-video', name: '照片视频' },
                { class: 'fas fa-wifi', name: 'WiFi' },
                { class: 'fas fa-signal', name: '信号' },
                { class: 'fas fa-bluetooth', name: '蓝牙' },
                { class: 'fas fa-bluetooth-b', name: '蓝牙B' },
                { class: 'fas fa-satellite', name: '卫星' },
                { class: 'fas fa-satellite-dish', name: '卫星天线' },
                { class: 'fas fa-tower-broadcast', name: '广播塔' },
                { class: 'fas fa-tower-cell', name: '信号塔' },
                { class: 'fas fa-battery-full', name: '满电池' },
                { class: 'fas fa-battery-half', name: '半电池' },
                { class: 'fas fa-battery-empty', name: '空电池' },
                { class: 'fas fa-plug', name: '插头' },
                { class: 'fas fa-charging-station', name: '充电站' },
                { class: 'fas fa-usb', name: 'USB' },
                { class: 'fab fa-usb', name: 'USB品牌' },
                { class: 'fas fa-ethernet', name: '以太网' },
                { class: 'fas fa-sd-card', name: 'SD卡' },
                { class: 'fas fa-sim-card', name: 'SIM卡' },
                { class: 'fas fa-hard-drive', name: '硬盘' },
                { class: 'fas fa-hdd', name: '机械硬盘' },
                { class: 'fas fa-memory', name: '内存' },
                { class: 'fas fa-microchip', name: '芯片' },
                { class: 'fas fa-cpu', name: 'CPU' },
                { class: 'fas fa-server', name: '服务器' },
                { class: 'fas fa-database', name: '数据库' },
                { class: 'fas fa-cloud', name: '云' },
                { class: 'fas fa-cloud-upload-alt', name: '云上传' },
                { class: 'fas fa-cloud-download-alt', name: '云下载' },
                { class: 'fas fa-network-wired', name: '有线网络' },
                { class: 'fas fa-router', name: '路由器' },
                { class: 'fas fa-ethernet', name: '网线' },
                { class: 'fas fa-robot', name: '机器人' },
                { class: 'fas fa-android', name: '安卓机器人' },
                { class: 'fas fa-gamepad', name: '游戏手柄' },
                { class: 'fas fa-vr-cardboard', name: 'VR眼镜' },
                { class: 'fas fa-glasses', name: '眼镜' },
                { class: 'fas fa-dna', name: 'DNA' },
                { class: 'fas fa-atom', name: '原子' },
                { class: 'fas fa-microscope', name: '显微镜' },
                { class: 'fas fa-telescope', name: '望远镜' },
                { class: 'fas fa-satellite', name: '人造卫星' },
                { class: 'fas fa-space-shuttle', name: '航天飞机' },
                { class: 'fas fa-rocket', name: '火箭' },
                { class: 'fas fa-drone', name: '无人机' },
                { class: 'fas fa-car', name: '汽车' },
                { class: 'fas fa-car-battery', name: '汽车电池' },
                { class: 'fas fa-solar-panel', name: '太阳能板' },
                { class: 'fas fa-wind', name: '风能' },
                { class: 'fas fa-bolt', name: '闪电' },
                { class: 'fas fa-zap', name: '电击' },
                { class: 'fas fa-fingerprint', name: '指纹' },
                { class: 'fas fa-qrcode', name: '二维码' },
                { class: 'fas fa-barcode', name: '条形码' },
                { class: 'fas fa-scan', name: '扫描' },
                { class: 'fas fa-print', name: '打印' },
                { class: 'fas fa-fax', name: '传真' },
                { class: 'fas fa-copy', name: '复印' },
                { class: 'fas fa-scanner', name: '扫描仪' }
            ]
        };

        // 获取所有图标
        function getAllIcons() {
            let allIcons = [];
            for (let category in fontAwesomeIcons) {
                allIcons = allIcons.concat(fontAwesomeIcons[category]);
            }
            return allIcons;
        }

        // 切换图标输入方式
        function toggleIconInput() {
            const iconType = document.querySelector('input[name="icon_type"]:checked').value;
            const classInput = document.getElementById('iconClassInput');
            const fileInput = document.getElementById('iconFileInput');
            const linkInput = document.getElementById('iconLinkInput');
            const imagePreview = document.getElementById('imagePreview');
            const imagePreviewText = document.getElementById('imagePreviewText');
            const linkImagePreview = document.getElementById('linkImagePreview');
            const linkImagePreviewText = document.getElementById('linkImagePreviewText');
            
            if (iconType === 'class') {
                classInput.style.display = 'block';
                fileInput.style.display = 'none';
                linkInput.style.display = 'none';
                document.getElementById('icon').required = true;
                document.getElementById('icon_file').required = false;
                document.getElementById('icon_link').required = false;
            } else if (iconType === 'upload') {
                classInput.style.display = 'none';
                fileInput.style.display = 'block';
                linkInput.style.display = 'none';
                document.getElementById('icon').required = false;
                document.getElementById('icon_link').required = false;
                // 当是新添加时，上传文件是必须的。编辑时不是。
                const isEditing = !!document.getElementById('navigationId').value;
                document.getElementById('icon_file').required = !isEditing;

                if (!imagePreview.src || imagePreview.src.endsWith('#')) {
                    imagePreview.style.display = 'none';
                    imagePreviewText.style.display = 'block';
                } else {
                    imagePreview.style.display = 'block';
                    imagePreviewText.style.display = 'none';
                }
            } else if (iconType === 'link') {
                classInput.style.display = 'none';
                fileInput.style.display = 'none';
                linkInput.style.display = 'block';
                document.getElementById('icon').required = false;
                document.getElementById('icon_file').required = false;
                // 当是新添加时，链接是必须的。编辑时不是。
                const isEditing = !!document.getElementById('navigationId').value;
                document.getElementById('icon_link').required = !isEditing;

                if (!linkImagePreview.src || linkImagePreview.src.endsWith('#')) {
                    linkImagePreview.style.display = 'none';
                    linkImagePreviewText.style.display = 'block';
                } else {
                    linkImagePreview.style.display = 'block';
                    linkImagePreviewText.style.display = 'none';
                }
            }
        }
        
        // 更新链接图标预览
        function updateLinkIconPreview(iconLink) {
            const linkImagePreview = document.getElementById('linkImagePreview');
            const linkImagePreviewText = document.getElementById('linkImagePreviewText');
            
            if (iconLink && iconLink.trim()) {
                linkImagePreview.src = iconLink;
                linkImagePreview.style.display = 'block';
                linkImagePreviewText.style.display = 'none';
                
                // 错误处理
                linkImagePreview.onerror = function() {
                    linkImagePreview.src = '#';
                    linkImagePreview.style.display = 'none';
                    linkImagePreviewText.style.display = 'block';
                    linkImagePreviewText.textContent = '无法加载图标，请检查链接';
                    linkImagePreviewText.style.color = '#e74c3c';
                };
                
                // 加载成功后重置文本样式
                linkImagePreview.onload = function() {
                    linkImagePreviewText.style.color = '#666';
                };
            } else {
                linkImagePreview.src = '#';
                linkImagePreview.style.display = 'none';
                linkImagePreviewText.style.display = 'block';
                linkImagePreviewText.textContent = '暂无预览';
                linkImagePreviewText.style.color = '#666';
            }
        }

        // 显示图标选择器
        function showIconPicker() {
            document.getElementById('iconPickerModal').classList.add('show');
            showIconCategory('all');
        }

        // 关闭图标选择器
        function closeIconPicker() {
            document.getElementById('iconPickerModal').classList.remove('show');
        }

        // 显示图标分类
        function showIconCategory(category) {
            // 更新分类按钮状态
            document.querySelectorAll('.icon-category-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            const targetBtn = event ? event.target : document.querySelector(`.icon-category-btn[onclick="showIconCategory('${category}')"]`);
            if (targetBtn) targetBtn.classList.add('active');

            // 获取图标数据
            let icons;
            if (category === 'all') {
                icons = getAllIcons();
            } else if (category === 'recent') {
                // 动态获取最近使用的图标
                icons = getRecentIcons();
            } else {
                icons = fontAwesomeIcons[category] || [];
            }

            // 生成图标网格
            renderIconGrid(icons);
        }

        // 渲染图标网格
        function renderIconGrid(icons) {
            const iconGrid = document.getElementById('iconGrid');
            iconGrid.innerHTML = '';

            if (icons.length === 0) {
                // 显示无结果提示
                const noResult = document.createElement('div');
                noResult.className = 'no-icon-results';
                noResult.innerHTML = `
                    <i class="fas fa-search"></i>
                    <p>未找到匹配的图标</p>
                    <small>请尝试其他关键词</small>
                `;
                iconGrid.appendChild(noResult);
                return;
            }

            icons.forEach(icon => {
                const iconItem = document.createElement('div');
                iconItem.className = 'icon-item';
                iconItem.innerHTML = `
                    <i class="${icon.class}"></i>
                    <span class="icon-name">${icon.name}</span>
                    <span class="icon-class">${icon.class}</span>
                `;
                iconItem.onclick = () => selectIcon(icon.class, icon.name);
                
                // 添加悬停效果
                iconItem.onmouseenter = function() {
                    this.style.transform = 'scale(1.05)';
                    this.style.boxShadow = '0 2px 8px rgba(0, 0, 0, 0.15)';
                };
                
                iconItem.onmouseleave = function() {
                    this.style.transform = 'scale(1)';
                    this.style.boxShadow = 'none';
                };
                
                iconGrid.appendChild(iconItem);
            });
        }

        // 选择图标
        function selectIcon(iconClass, iconName) {
            document.getElementById('icon').value = iconClass;
            document.getElementById('selectedIconPreview').className = iconClass;
            document.getElementById('selectedIconText').textContent = iconName;
            document.getElementById('selectedIconClass').textContent = iconClass;
            
            // 保存到最近使用列表
            saveRecentIcon(iconClass, iconName);
            closeIconPicker();
        }

        // 更新图标预览
        function updateIconPreview(iconClass) {
            if (iconClass && iconClass.trim()) {
                document.getElementById('selectedIconPreview').className = iconClass;
                // 尝试从图标库中找到对应的名称
                const allIcons = getAllIcons();
                const foundIcon = allIcons.find(icon => icon.class === iconClass);
                const iconName = foundIcon ? foundIcon.name : iconClass;
                
                document.getElementById('selectedIconText').textContent = iconName;
                document.getElementById('selectedIconClass').textContent = iconClass;
            } else {
                document.getElementById('selectedIconPreview').className = 'fas fa-question-circle';
                document.getElementById('selectedIconText').textContent = '请选择图标';
                document.getElementById('selectedIconClass').textContent = '点击选择';
            }
        }

        // 搜索图标
        function filterIcons(searchTerm) {
            const allIcons = getAllIcons();
            const filteredIcons = allIcons.filter(icon => 
                icon.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                icon.class.toLowerCase().includes(searchTerm.toLowerCase())
            );
            renderIconGrid(filteredIcons);
        }
        
        // 多分类选择器功能
        function toggleCategoryDropdown() {
            const dropdown = document.getElementById('categoryDropdown');
            dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
        }
        
        function updateSelectedCategories() {
            const checkboxes = document.querySelectorAll('input[name="category_ids[]"]:checked');
            const selectedContainer = document.getElementById('selectedCategories');
            const placeholder = selectedContainer.querySelector('.placeholder');
            
            // 移除现有的标签
            selectedContainer.querySelectorAll('.category-tag').forEach(tag => tag.remove());
            
            if (checkboxes.length === 0) {
                placeholder.style.display = 'inline';
                document.getElementById('category_id').value = '';
            } else {
                placeholder.style.display = 'none';
                
                // 为兼容性设置第一个选中的分类到隐藏的select
                const firstSelectedValue = checkboxes[0].value;
                document.getElementById('category_id').value = firstSelectedValue;
                
                // 创建分类标签
                checkboxes.forEach(checkbox => {
                    const categoryName = checkbox.parentElement.querySelector('.category-name').textContent;
                    const tag = document.createElement('span');
                    tag.className = 'category-tag';
                    tag.innerHTML = `
                        ${categoryName}
                        <i class="fas fa-times" onclick="removeCategoryTag(${checkbox.value})"></i>
                    `;
                    selectedContainer.insertBefore(tag, selectedContainer.querySelector('.dropdown-arrow'));
                });
            }

            // 更新标签选择区域
            toggleTagSection();
        }

        function removeCategoryTag(categoryId) {
            const checkbox = document.querySelector(`input[name="category_ids[]"][value="${categoryId}"]`);
            if (checkbox) {
                checkbox.checked = false;
                updateSelectedCategories();
            }
        }
        
        function setCategoriesForEdit(categoryIds) {
            // 重置所有复选框
            document.querySelectorAll('input[name="category_ids[]"]').forEach(checkbox => {
                checkbox.checked = false;
            });
            
            // 设置选中的分类
            if (categoryIds && categoryIds.length > 0) {
                categoryIds.forEach(categoryId => {
                    const checkbox = document.querySelector(`input[name="category_ids[]"][value="${categoryId}"]`);
                    if (checkbox) {
                        checkbox.checked = true;
                    }
                });
            }
            
            updateSelectedCategories();
        }
        
        // 点击外部关闭分类下拉框
        document.addEventListener('click', function(event) {
            const categorySelector = document.querySelector('.category-selector');
            const dropdown = document.getElementById('categoryDropdown');
            
            if (categorySelector && !categorySelector.contains(event.target)) {
                dropdown.style.display = 'none';
            }
        });

        // 显示添加模态框
        function showAddModal() {
            document.getElementById('modalTitle').textContent = '添加导航';
            document.getElementById('formAction').value = 'add';
            document.getElementById('navigationId').value = '';
            document.getElementById('currentIcon').value = '';
            
            // 重置表单
            document.getElementById('navigationForm').reset();
            
            // 重置分类选择
            setCategoriesForEdit([]);

            // 重置标签选择
            selectedTagIds = [];
            updateSelectedTagsDisplay();

            // 重置图标预览
            updateIconPreview('');
            const imagePreview = document.getElementById('imagePreview');
            const imagePreviewText = document.getElementById('imagePreviewText');
            imagePreview.src = '#';
            imagePreview.style.display = 'none';
            imagePreviewText.style.display = 'block';
            
            toggleIconInput();
            document.getElementById('navigationModal').classList.add('show');
        }
        
        // ==================== 标签选择功能 ====================

        let allTags = []; // 存储所有标签数据
        let selectedTagIds = []; // 存储选中的标签ID

        // 切换标签下拉框显示/隐藏
        function toggleTagDropdown() {
            const dropdown = document.getElementById('tagDropdown');
            const isHidden = dropdown.style.display === 'none' || !dropdown.style.display;

            if (isHidden) {
                dropdown.style.display = 'block';
                dropdown.classList.add('show');
                // 加载标签数据
                loadTags();
            } else {
                closeTagDropdown();
            }
        }

        // 关闭标签下拉框
        function closeTagDropdown() {
            const dropdown = document.getElementById('tagDropdown');
            dropdown.style.display = 'none';
            dropdown.classList.remove('show');
        }

        // 加载标签数据
        async function loadTags() {
            const selectedCategories = getSelectedCategoryIds();

            if (selectedCategories.length === 0) {
                showNoTags();
                return;
            }

            // 显示加载状态
            document.getElementById('tagLoading').style.display = 'block';
            document.getElementById('tagList').style.display = 'none';
            document.getElementById('noTags').style.display = 'none';

            try {
                // 构建查询参数
                const params = new URLSearchParams({
                    category_ids: selectedCategories.join(',')
                });

                // 发送AJAX请求获取标签数据
                const response = await fetch(`<?php echo getUrl('api/tags'); ?>?${params}`);

                if (!response.ok) {
                    throw new Error('获取标签失败');
                }

                const data = await response.json();
                allTags = data.tags || [];

                if (allTags.length === 0) {
                    showNoTags();
                } else {
                    showTagList();
                }
            } catch (error) {
                console.error('加载标签失败:', error);
                showNoTags();
            }
        }

        // 显示无标签状态
        function showNoTags() {
            document.getElementById('tagLoading').style.display = 'none';
            document.getElementById('tagList').style.display = 'none';
            document.getElementById('noTags').style.display = 'block';
        }

        // 显示标签列表
        function showTagList() {
            const tagList = document.getElementById('tagList');
            const categoryNames = getCategoryNames();

            tagList.innerHTML = '';

            allTags.forEach(tag => {
                const option = document.createElement('label');
                option.className = 'tag-option';

                const isChecked = selectedTagIds.includes(tag.id);
                const categoryName = categoryNames[tag.category_id] || '未知分类';

                option.innerHTML = `
                    <input type="checkbox"
                           name="tag_ids[]"
                           value="${tag.id}"
                           ${isChecked ? 'checked' : ''}
                           onchange="handleTagChange(${tag.id}, this.checked)">
                    <span class="tag-name">${tag.name_cn}</span>
                    <span class="tag-category">${categoryName}</span>
                `;

                tagList.appendChild(option);
            });

            document.getElementById('tagLoading').style.display = 'none';
            document.getElementById('tagList').style.display = 'block';
            document.getElementById('noTags').style.display = 'none';
        }

        // 处理标签选择变化
        function handleTagChange(tagId, isChecked) {
            if (isChecked) {
                if (!selectedTagIds.includes(tagId)) {
                    selectedTagIds.push(tagId);
                }
            } else {
                const index = selectedTagIds.indexOf(tagId);
                if (index > -1) {
                    selectedTagIds.splice(index, 1);
                }
            }

            updateSelectedTagsDisplay();
        }

        // 更新选中标签的显示
        function updateSelectedTagsDisplay() {
            const container = document.getElementById('selectedTags');

            if (selectedTagIds.length === 0) {
                container.innerHTML = '<span class="placeholder">请选择标签</span><i class="fas fa-chevron-down dropdown-arrow"></i>';
                return;
            }

            let html = '<div class="selected-tags-container">';

            selectedTagIds.forEach(tagId => {
                const tag = allTags.find(t => t.id === tagId);
                if (tag) {
                    html += `
                        <span class="selected-tag">
                            ${tag.name_cn}
                            <span class="remove-tag" onclick="removeTag(${tagId})">&times;</span>
                        </span>
                    `;
                }
            });

            html += '</div><i class="fas fa-chevron-down dropdown-arrow"></i>';
            container.innerHTML = html;
        }

        // 移除标签
        function removeTag(tagId) {
            const index = selectedTagIds.indexOf(tagId);
            if (index > -1) {
                selectedTagIds.splice(index, 1);
            }

            // 更新复选框状态
            const checkbox = document.querySelector(`input[name="tag_ids[]"][value="${tagId}"]`);
            if (checkbox) {
                checkbox.checked = false;
            }

            updateSelectedTagsDisplay();
        }

        // 获取选中的分类ID
        function getSelectedCategoryIds() {
            const checkboxes = document.querySelectorAll('input[name="category_ids[]"]:checked');
            return Array.from(checkboxes).map(cb => parseInt(cb.value));
        }

        // 获取分类名称映射
        function getCategoryNames() {
            const categoryMap = {};
            const categories = document.querySelectorAll('.category-option input[name="category_ids[]"]');

            categories.forEach(category => {
                const label = category.closest('.category-option');
                const name = label.querySelector('.category-name').textContent;
                categoryMap[parseInt(category.value)] = name;
            });

            return categoryMap;
        }

        // 显示/隐藏标签选择区域
        function toggleTagSection() {
            const tagFormGroup = document.getElementById('tagFormGroup');
            const selectedCategories = getSelectedCategoryIds();

            if (selectedCategories.length > 0) {
                tagFormGroup.style.display = 'block';
                // 重新加载标签
                loadTags();
            } else {
                tagFormGroup.style.display = 'none';
                // 清空已选标签
                selectedTagIds = [];
                updateSelectedTagsDisplay();
            }
        }

        // ==================== 标签选择功能结束 ====================

        // 编辑导航
        function editNavigation(navigation) {
            document.getElementById('modalTitle').textContent = '编辑导航';
            document.getElementById('navigationForm').reset();
            document.getElementById('formAction').value = 'edit';
            document.getElementById('navigationId').value = navigation.id;
            document.getElementById('currentIcon').value = navigation.icon;
            document.getElementById('name').value = navigation.name;
            document.getElementById('url').value = navigation.url;
            
            // 打开编辑时自动获取目标网站的图标
            if (navigation.url) {
                // 延迟获取，确保模态框完全加载
                setTimeout(() => {
                    autoGetWebsiteIcon(navigation.url);
                    
                    // 同时尝试获取网站描述（如果描述为空）
                    if (!navigation.description || navigation.description.trim() === '') {
                        autoGetWebsiteDescription(navigation.url);
                    }
                }, 500);
            }
            
            // 处理分类设置 - 兼容新旧版本
            let categoryIds = [];
            if (navigation.category_ids && Array.isArray(navigation.category_ids)) {
                categoryIds = navigation.category_ids;
            } else if (navigation.category_id) {
                categoryIds = [navigation.category_id];
            }
            setCategoriesForEdit(categoryIds);

            // 处理标签设置
            selectedTagIds = navigation.tag_ids || [];
            updateSelectedTagsDisplay();

            document.getElementById('description').value = navigation.description || '';
            document.getElementById('sort').value = navigation.sort;
            document.getElementById('is_favorite').checked = (navigation.is_favorite == 1);
            
            const imagePreview = document.getElementById('imagePreview');
            const imagePreviewText = document.getElementById('imagePreviewText');
            const linkImagePreview = document.getElementById('linkImagePreview');
            const linkImagePreviewText = document.getElementById('linkImagePreviewText');

            // 重置所有预览
            imagePreview.src = '#';
            imagePreview.style.display = 'none';
            imagePreviewText.style.display = 'block';
            linkImagePreview.src = '#';
            linkImagePreview.style.display = 'none';
            linkImagePreviewText.style.display = 'block';

            // 设置图标类型
            if (navigation.icon_type === 'class') {
                document.querySelector('input[name="icon_type"][value="class"]').checked = true;
                document.getElementById('icon').value = navigation.icon;
                updateIconPreview(navigation.icon);
            } else if (navigation.icon_type === 'link') {
                document.querySelector('input[name="icon_type"][value="link"]').checked = true;
                document.getElementById('icon_link').value = navigation.icon;
                updateLinkIconPreview(navigation.icon);
                updateIconPreview('');
            } else { // 'url' 或其他类型
                document.querySelector('input[name="icon_type"][value="upload"]').checked = true;
                updateIconPreview('');
                if (navigation.icon) {
                    imagePreview.src = navigation.icon;
                    imagePreview.style.display = 'block';
                    imagePreviewText.style.display = 'none';
                }
            }
            toggleIconInput();
            
            document.getElementById('navigationModal').classList.add('show');
        }
        
        // 删除导航
        function deleteNavigation(id, name) {
            document.getElementById('deleteNavigationId').value = id;
            document.getElementById('deleteNavigationName').textContent = name;
            document.getElementById('deleteModal').classList.add('show');
        }
        
        // 确认删除
        function confirmDelete() {
            document.getElementById('deleteForm').submit();
        }
        
        // 关闭模态框
        function closeModal() {
            document.getElementById('navigationModal').classList.remove('show');
            document.getElementById('navigationForm').reset();
        }
        
        function closeDeleteModal() {
            document.getElementById('deleteModal').classList.remove('show');
        }
        
        // 显示分类弹窗
        function showCategoryModal(navId, categories) {
            const modalContent = document.getElementById('categoryModalContent');
            modalContent.innerHTML = '';
            
            if (categories && categories.length > 0) {
                categories.forEach(category => {
                    const categoryItem = document.createElement('div');
                    categoryItem.className = 'category-modal-item';
                    categoryItem.innerHTML = `
                        <div class="category-item-content">
                            <i class="${category.icon || 'fas fa-folder'}"></i>
                            <span class="category-name">${category.name}</span>
                        </div>
                    `;
                    modalContent.appendChild(categoryItem);
                });
            } else {
                modalContent.innerHTML = '<div class="empty-categories">该导航暂未绑定任何分类</div>';
            }
            
            document.getElementById('categoryModal').classList.add('show');
        }
        
        // 关闭分类弹窗
        function closeCategoryModal() {
            document.getElementById('categoryModal').classList.remove('show');
        }

        // 切换常用状态
        function toggleFavorite(id, isChecked) {
            const switchElement = event.target;
            const formData = new FormData();
            formData.append('id', id);
            formData.append('is_favorite', isChecked ? 1 : 0);
            
            fetch('/admin/navigations.php?ajax=toggle_favorite', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('服务器返回错误: ' + response.status);
                }
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error('服务器响应格式错误，期望JSON但收到: ' + contentType);
                }
                return response.json();
            })
            .then(data => {
                if (!data.success) {
                    const errorMessage = data.error ? `更新失败: ${data.error}` : '更新失败，请重试';
                    showAlert(errorMessage, 'error');
                    switchElement.checked = !isChecked;
                } else {
                    showAlert('常用状态更新成功', 'success');
                }
            })
            .catch(error => {
                console.error('切换常用状态错误:', error);
                switchElement.checked = !isChecked;
                showAlert('操作失败: ' + error.message, 'error');
            });
        }
        
        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modal = document.getElementById('navigationModal');
            const deleteModal = document.getElementById('deleteModal');
            const iconPickerModal = document.getElementById('iconPickerModal');
            const categoryModal = document.getElementById('categoryModal');
            
            if (event.target === modal) {
                closeModal();
            }
            if (event.target === deleteModal) {
                closeDeleteModal();
            }
            if (event.target === iconPickerModal) {
                closeIconPicker();
            }
            if (event.target === categoryModal) {
                closeCategoryModal();
            }

            // 关闭标签下拉框
            const tagDropdown = document.getElementById('tagDropdown');
            const tagSelector = document.getElementById('selectedTags');
            if (tagDropdown && tagSelector && !tagSelector.contains(event.target) && !tagDropdown.contains(event.target)) {
                closeTagDropdown();
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            // 初始化时调用，处理所有单选按钮
            document.querySelectorAll('input[name="icon_type"]').forEach(radio => {
                radio.addEventListener('change', toggleIconInput);
            });

            // 为URL输入框添加事件监听器，自动获取网站图标和描述
            const urlInput = document.getElementById('url');
            urlInput.addEventListener('blur', function() {
                if (this.value.trim()) {
                    autoGetWebsiteIcon(this.value.trim());
                    autoGetWebsiteDescription(this.value.trim());
                }
            });

            // 添加延迟获取功能，用户输入完成后自动尝试获取
            let urlInputTimeout;
            urlInput.addEventListener('input', function() {
                clearTimeout(urlInputTimeout);
                urlInputTimeout = setTimeout(() => {
                    if (this.value.trim()) {
                        autoGetWebsiteIcon(this.value.trim());
                        autoGetWebsiteDescription(this.value.trim());
                    }
                }, 1000); // 1秒延迟，避免频繁请求
            });

            // 文件上传预览和拖拽功能
            const iconFileInput = document.getElementById('icon_file');
            const imagePreview = document.getElementById('imagePreview');
            const imagePreviewText = document.getElementById('imagePreviewText');
            const imagePreviewContainer = document.querySelector('.image-preview-container');
            
            // 文件选择预览
            iconFileInput.addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    previewImage(this.files[0]);
                }
            });
            
            // 拖拽上传功能
            if (imagePreviewContainer) {
                // 拖拽悬停样式变化
                ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                    imagePreviewContainer.addEventListener(eventName, preventDefaults, false);
                });
                
                function preventDefaults(e) {
                    e.preventDefault();
                    e.stopPropagation();
                }
                
                ['dragenter', 'dragover'].forEach(eventName => {
                    imagePreviewContainer.addEventListener(eventName, highlight, false);
                });
                
                ['dragleave', 'drop'].forEach(eventName => {
                    imagePreviewContainer.addEventListener(eventName, unhighlight, false);
                });
                
                function highlight() {
                    imagePreviewContainer.classList.add('drag-over');
                }
                
                function unhighlight() {
                    imagePreviewContainer.classList.remove('drag-over');
                }
                
                // 处理拖拽文件
                imagePreviewContainer.addEventListener('drop', handleDrop, false);
                
                function handleDrop(e) {
                    const dt = e.dataTransfer;
                    const files = dt.files;
                    
                    if (files.length > 0) {
                        iconFileInput.files = files;
                        previewImage(files[0]);
                    }
                }
                
                // 点击容器触发文件选择
                imagePreviewContainer.addEventListener('click', function() {
                    iconFileInput.click();
                });
            }
            
            // 图片预览函数
            function previewImage(file) {
                // 检查文件类型
                if (!file.type.match('image.*')) {
                    showAlert('请上传图片文件！', 'error');
                    return;
                }
                
                // 检查文件大小（限制1MB）
                if (file.size > 1024 * 1024) {
                    showAlert('文件大小不能超过1MB！', 'error');
                    return;
                }
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    imagePreview.style.display = 'block';
                    
                    // 添加删除预览按钮
                    let removeBtn = document.getElementById('removeImagePreview');
                    if (!removeBtn) {
                        removeBtn = document.createElement('button');
                        removeBtn.id = 'removeImagePreview';
                        removeBtn.className = 'remove-image-preview-btn';
                        removeBtn.innerHTML = '<i class="fas fa-times"></i>';
                        removeBtn.onclick = function(e) {
                            e.stopPropagation();
                            clearImagePreview();
                        };
                        imagePreviewContainer.appendChild(removeBtn);
                    }
                    
                    imagePreviewText.style.display = 'none';
                }
                reader.readAsDataURL(file);
            }
            
            // 清除图片预览
            function clearImagePreview() {
                imagePreview.src = '#';
                imagePreview.style.display = 'none';
                imagePreviewText.style.display = 'block';
                
                const removeBtn = document.getElementById('removeImagePreview');
                if (removeBtn) {
                    removeBtn.remove();
                }
                
                // 清空文件输入
                iconFileInput.value = '';
            }
            
            // 自动获取网站图标函数 - 加强版
            function autoGetWebsiteIcon(url) {
                try {
                    // 确保URL格式正确
                    if (!url.startsWith('http://') && !url.startsWith('https://')) {
                        url = 'https://' + url;
                    }
                    
                    const urlObj = new URL(url);
                    const domain = urlObj.hostname;
                    
                    // 定义可能的favicon路径 - 加强版，包含更多的可能路径
                    const faviconUrls = [
                        `${urlObj.protocol}//${domain}/favicon.ico`,
                        `${urlObj.protocol}//${domain}/favicon.png`,
                        `${urlObj.protocol}//${domain}/favicon.jpg`,
                        `${urlObj.protocol}//${domain}/apple-touch-icon.png`,
                        `${urlObj.protocol}//${domain}/apple-touch-icon-precomposed.png`,
                        `${urlObj.protocol}//${domain}/touch-icon-iphone.png`,
                        `${urlObj.protocol}//${domain}/favicon-32x32.png`,
                        `${urlObj.protocol}//${domain}/favicon-16x16.png`,
                        `${urlObj.protocol}//${domain}/android-chrome-192x192.png`,
                        `${urlObj.protocol}//${domain}/android-chrome-512x512.png`,
                        `${urlObj.protocol}//${domain}/mstile-150x150.png`,
                        // 使用外部服务获取图标
                        `https://www.google.com/s2/favicons?domain=${domain}&sz=64`,
                        `https://besticon-demo.herokuapp.com/icon?url=${domain}&size=64`,
                        `https://icon.horse/icon/${domain}`,
                        `https://favicon.yandex.net/favicon/${domain}`
                    ];
                    
                    // 尝试获取favicon的函数
                    function tryGetFavicon(urls, index = 0) {
                        if (index >= urls.length) {
                            // 所有尝试都失败了，切换到上传图标模式
                            document.querySelector('input[name="icon_type"][value="upload"]').checked = true;
                            toggleIconInput();
                            return;
                        }
                        
                        const testImage = new Image();
                        // 设置超时时间，避免长时间等待
                        testImage.timeout = 5000; // 5秒
                        
                        const timer = setTimeout(() => {
                            testImage.src = ''; // 取消加载
                            tryGetFavicon(urls, index + 1);
                        }, testImage.timeout);
                        
                        testImage.onload = function() {
                            clearTimeout(timer);
                            // 只有当图片尺寸大于16x16时才认为是有效图标
                            if (this.width > 16 && this.height > 16) {
                                // 设置图标链接输入
                                document.querySelector('input[name="icon_type"][value="link"]').checked = true;
                                document.getElementById('icon_link').value = urls[index];
                                updateLinkIconPreview(urls[index]);
                                toggleIconInput(); // 切换到链接输入模式
                            } else {
                                tryGetFavicon(urls, index + 1);
                            }
                        };
                        
                        testImage.onerror = function() {
                            clearTimeout(timer);
                            tryGetFavicon(urls, index + 1);
                        };
                        
                        testImage.src = urls[index];
                    }
                    
                    // 开始尝试获取favicon
                    tryGetFavicon(faviconUrls);
                } catch (error) {
                    console.error('获取网站图标失败:', error);
                    // 出错时也切换到上传图标模式
                    document.querySelector('input[name="icon_type"][value="upload"]').checked = true;
                    toggleIconInput();
            }
        }

        // 自动获取目标网站网页描述内容
        function autoGetWebsiteDescription(url) {
            try {
                // 确保URL格式正确
                if (!url.startsWith('http://') && !url.startsWith('https://')) {
                    url = 'https://' + url;
                }
                
                const urlObj = new URL(url);
                
                // 获取描述输入框引用
                const descriptionInput = document.getElementById('description');
                
                // 只在描述框为空时填充，避免覆盖用户手动输入的内容
                if (!descriptionInput.value.trim()) {
                    // 显示加载中状态
                    descriptionInput.placeholder = '正在获取网页描述...';
                    
                    // 定义多个备用代理服务
                    const proxyServices = [
                        'https://api.allorigins.win/raw?url=',
                        'https://api.codetabs.com/v1/proxy?quest=',
                        'https://corsproxy.io/?' 
                    ];
                    
                    // 尝试使用不同的代理服务获取网页内容
                    function tryWithProxyService(proxyIndex = 0) {
                        if (proxyIndex >= proxyServices.length) {
                            console.error('所有代理服务都失败了');
                            descriptionInput.placeholder = '获取描述失败，请手动输入';
                            return;
                        }
                        
                        const proxyUrl = proxyServices[proxyIndex] + encodeURIComponent(url);
                        console.log(`尝试使用代理服务 ${proxyIndex + 1}: ${proxyUrl}`);
                        
                        fetch(proxyUrl, {
                            method: 'GET',
                            headers: {
                                'Content-Type': 'text/plain',
                                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
                            },
                            timeout: 8000 // 8秒超时，给代理服务足够的响应时间
                        })
                        .then(response => {
                            if (!response.ok) {
                                throw new Error(`代理服务响应错误: ${response.status}`);
                            }
                            return response.text();
                        })
                        .then(html => {
                            // 解析HTML获取标题和meta描述
                            const parser = new DOMParser();
                            const doc = parser.parseFromString(html, 'text/html');
                            
                            let description = '';
                            
                            // 尝试获取meta description，增加健壮性，考虑大小写和不同格式
                            const metaDesc = doc.querySelector('meta[name="description"]') || 
                                           doc.querySelector('meta[name="Description"]');
                            if (metaDesc && metaDesc.content) {
                                description = metaDesc.content.trim();
                                console.log('成功获取meta description:', description);
                            }
                            
                            // 如果没有meta描述，尝试获取og:description
                            if (!description) {
                                const ogDesc = doc.querySelector('meta[property="og:description"]') ||
                                             doc.querySelector('meta[name="og:description"]');
                                if (ogDesc && ogDesc.content) {
                                    description = ogDesc.content.trim();
                                    console.log('成功获取og:description:', description);
                                }
                            }
                            
                            // 如果还是没有描述，尝试获取网页标题
                            if (!description) {
                                const title = doc.querySelector('title');
                                if (title && title.textContent) {
                                    description = title.textContent.trim();
                                    console.log('使用网页标题作为描述:', description);
                                }
                            }
                            
                            // 如果获取到了描述并且不为空，设置到输入框中
                            if (description) {
                                // 限制描述长度，避免过长
                                if (description.length > 200) {
                                    description = description.substring(0, 200) + '...';
                                }
                                descriptionInput.value = description;
                                descriptionInput.placeholder = '描述已自动获取';
                            } else {
                                // 如果没有获取到描述，提示用户
                                descriptionInput.placeholder = '未找到网页描述，请手动输入';
                                console.log('没有找到任何可用的描述信息');
                            }
                        })
                        .catch(error => {
                            console.error(`使用代理服务 ${proxyIndex + 1} 获取网页描述失败:`, error);
                            // 尝试下一个代理服务
                            tryWithProxyService(proxyIndex + 1);
                        });
                    }
                    
                    // 开始尝试获取网页描述
                    tryWithProxyService();
                }
            } catch (error) {
                console.error('获取网页描述失败:', error);
                const descriptionInput = document.getElementById('description');
                descriptionInput.placeholder = '获取描述失败，请手动输入';
            }
        }

            // 初始加载时根据默认选中的radio button设置
            toggleIconInput();
            
            // 添加图标选择器的CSS样式
            const style = document.createElement('style');
            style.innerHTML = `
                .no-icon-results {
                    text-align: center;
                    padding: 40px 20px;
                    color: #666;
                }
                .no-icon-results i {
                    font-size: 48px;
                    margin-bottom: 15px;
                    opacity: 0.5;
                }
                .icon-item {
                    transition: transform 0.2s ease, box-shadow 0.2s ease;
                    cursor: pointer;
                }
                .icon-input-group {
                    display: flex;
                    gap: 10px;
                    align-items: flex-start;
                }
                .selected-icon-display {
                    display: flex;
                    align-items: center;
                    gap: 10px;
                    padding: 8px 12px;
                    border: 1px solid #ddd;
                    border-radius: 4px;
                    cursor: pointer;
                    background-color: #f9f9f9;
                    min-width: 200px;
                }
                .selected-icon-display:hover {
                    background-color: #f1f1f1;
                }
                #selectedIconPreview {
                    font-size: 24px;
                    color: #4a6cf7;
                }
                .icon-display-text {
                    flex: 1;
                }
                .icon-class-text {
                    font-size: 12px;
                    color: #666;
                    display: block;
                }
                .icon-dropdown-arrow {
                    font-size: 12px;
                    color: #999;
                }
                .image-preview-container {
                    width: 100%;
                    height: 120px;
                    border: 2px dashed #ddd;
                    border-radius: 4px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-bottom: 10px;
                    background-color: #f9f9f9;
                    position: relative;
                }
                .image-preview-container:hover {
                    border-color: #4a6cf7;
                    background-color: #f0f4ff;
                }
                .image-preview-container.drag-over {
                    border-color: #2ecc71;
                    background-color: #f0fdf4;
                }
                #imagePreview {
                    max-width: 100%;
                    max-height: 100%;
                    object-fit: contain;
                }
                #imagePreviewText {
                    color: #666;
                    text-align: center;
                    margin: 0;
                    padding: 0 20px;
                    width: 100%;
                }
                #linkImagePreviewText {
                    color: #666;
                    text-align: center;
                    margin: 0;
                    padding: 0 20px;
                    width: 100%;
                }
                .remove-image-preview-btn {
                    position: absolute;
                    top: 10px;
                    right: 10px;
                    background-color: #e74c3c;
                    color: white;
                    border: none;
                    border-radius: 50%;
                    width: 24px;
                    height: 24px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    cursor: pointer;
                    z-index: 10;
                }
                .remove-image-preview-btn:hover {
                    background-color: #c0392b;
                }
            `;
            document.head.appendChild(style);
        });
    </script>
</body>
</html>